package com.bookocean.controller;

import com.bookocean.application.common.Result;
import com.bookocean.application.service.UserProfileApplicationService;
import com.bookocean.controller.dto.UserAgreementDto;
import com.bookocean.controller.dto.UserProfileDto;
import com.bookocean.controller.dto.BadgeDto;
import com.bookocean.domain.utils.UserContextHolder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import java.util.List;

/**
 * 用户档案控制器（灵曜页面专用）
 * 
 * @author BookOcean
 * @since 2024-01-01
 */
@Slf4j
@RestController
@RequestMapping("/user-profile")
@RequiredArgsConstructor
public class UserProfileController {

    private final UserProfileApplicationService userProfileApplicationService;

    /**
     * 获取用户完整档案信息（灵曜页面数据）
     * 
     * @return 用户档案信息
     */
    @GetMapping("/profile")
    public Result<UserProfileDto> getUserProfile() {
        Long currentUserId = UserContextHolder.getUserId();
        log.info("获取用户档案信息，userId: {}", currentUserId);
        
        UserProfileDto userProfile = userProfileApplicationService.getUserProfile(currentUserId);
        return Result.success(userProfile);
    }

    /**
     * 获取指定用户的档案信息
     * 
     * @param userId 用户ID
     * @return 用户档案信息
     */
    @GetMapping("/profile/{userId}")
    public Result<UserProfileDto> getUserProfileById(@PathVariable Long userId) {
        log.info("获取指定用户档案信息，userId: {}", userId);
        
        UserProfileDto userProfile = userProfileApplicationService.getUserProfile(userId);
        return Result.success(userProfile);
    }

    /**
     * 获取用户徽章列表
     * 
     * @return 徽章列表
     */
    @GetMapping("/badges")
    public Result<List<BadgeDto>> getUserBadges() {
        Long currentUserId = UserContextHolder.getUserId();
        log.info("获取用户徽章列表，userId: {}", currentUserId);
        
        List<BadgeDto> badges = userProfileApplicationService.getUserBadges(currentUserId);
        return Result.success(badges);
    }

    /**
     * 获取指定用户的徽章列表
     * 
     * @param userId 用户ID
     * @return 徽章列表
     */
    @GetMapping("/badges/{userId}")
    public Result<List<BadgeDto>> getUserBadgesById(@PathVariable Long userId) {
        log.info("获取指定用户徽章列表，userId: {}", userId);
        
        List<BadgeDto> badges = userProfileApplicationService.getUserBadges(userId);
        return Result.success(badges);
    }

    /**
     * 更新用户个性签名
     * 
     * @param signature 个性签名
     * @return 更新结果
     */
    @PutMapping("/signature")
    public Result<Boolean> updateSignature(@RequestParam @NotBlank(message = "个性签名不能为空") String signature) {
        Long currentUserId = UserContextHolder.getUserId();
        log.info("更新用户个性签名，userId: {}, signature: {}", currentUserId, signature);
        
        // 验证签名长度
        if (signature.length() > 100) {
            return Result.error("个性签名不能超过100个字符");
        }
        
        boolean result = userProfileApplicationService.updateUserSignature(currentUserId, signature);
        return Result.success(result);
    }

    /**
     * 记录用户协议同意
     * 
     * @param agreementData 协议同意数据
     * @return 记录结果
     */
    @PostMapping("/agreement")
    public Result<Boolean> recordUserAgreement(@RequestBody UserAgreementDto agreementData) {
        Long currentUserId = UserContextHolder.getUserId();
        log.info("记录用户协议同意，userId: {}, agreementType: {}, version: {}", 
                currentUserId, agreementData.getAgreementType(), agreementData.getAgreementVersion());
        
        // 设置当前用户ID
        agreementData.setUserId(currentUserId);
        
        boolean result = userProfileApplicationService.recordUserAgreement(agreementData);
        return Result.success(result);
    }

    /**
     * 检查用户是否已同意协议
     * 
     * @param agreementType 协议类型
     * @param agreementVersion 协议版本
     * @return 是否已同意
     */
    @GetMapping("/agreement/check")
    public Result<Boolean> checkUserAgreement(@RequestParam String agreementType, 
                                            @RequestParam(required = false) String agreementVersion) {
        try {
            Long currentUserId = UserContextHolder.getUserId();
            log.info("检查用户协议同意状态，userId: {}, agreementType: {}, version: {}", 
                    currentUserId, agreementType, agreementVersion);
            
            boolean hasAgreed = userProfileApplicationService.checkUserAgreement(currentUserId, agreementType, agreementVersion);
            return Result.success(hasAgreed);
        } catch (Exception e) {
            log.warn("检查协议状态时获取用户ID失败，可能用户未登录: {}", e.getMessage());
            // 如果用户未登录，返回false表示未同意协议
            return Result.success(false);
        }
    }

    /**
     * 获取用户积分信息
     * 
     * @return 用户积分信息
     */
    @GetMapping("/points")
    public Result<UserProfileDto.UserPoints> getUserPoints() {
        Long currentUserId = UserContextHolder.getUserId();
        log.info("获取用户积分信息，userId: {}", currentUserId);
        
        UserProfileDto.UserPoints points = userProfileApplicationService.getUserPoints(currentUserId);
        return Result.success(points);
    }

    /**
     * 获取指定用户的积分信息
     * 
     * @param userId 用户ID
     * @return 用户积分信息
     */
    @GetMapping("/points/{userId}")
    public Result<UserProfileDto.UserPoints> getUserPointsById(@PathVariable Long userId) {
        log.info("获取指定用户积分信息，userId: {}", userId);
        
        UserProfileDto.UserPoints points = userProfileApplicationService.getUserPoints(userId);
        return Result.success(points);
    }
}
